//
//  APIService.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import Foundation
import Combine
import SwiftUI
import UIKit

// MARK: - 空响应模型
struct EmptyResponse: Codable {
    // 空结构体，用于表示不需要返回具体数据的API响应
}

// MARK: - 社区分类模型
struct CommunityCategory: Codable, Identifiable {
    let id: String
    let name: String
}

// MARK: - 社区内容模型
struct CommunityNote: Codable, Identifiable {
    let id: String
    let title: String
    let content: String
    let images: [String]
    let video: String?
    let authorId: String
    let authorName: String
    let authorAvatar: String
    let likeNum: Int
    let commentNum: Int
    let shareNum: Int
    let createTime: String
    let userIsLike: Bool
    let categoryId: String?
    let categoryName: String?
    let topicId: String?
    let topicName: String?
    
    enum CodingKeys: String, CodingKey {
        case id, title, content, images, video
        case authorId = "author_id"
        case authorName = "author_name"
        case authorAvatar = "author_avatar"
        case likeNum = "like_num"
        case commentNum = "comment_num"
        case shareNum = "share_num"
        case createTime = "create_time"
        case userIsLike = "user_is_like"
        case categoryId = "category_id"
        case categoryName = "category_name"
        case topicId = "topic_id"
        case topicName = "topic_name"
    }
}

// MARK: - 推荐作者模型
struct RecommendAuthor: Codable, Identifiable {
    let id: String
    let authorId: String
    let authorName: String
    let authorAvatar: String
    let signature: String
    let fansNum: Int
    let noteNum: Int
    let isConcerned: Bool
    let noteImages: [String]
    
    enum CodingKeys: String, CodingKey {
        case id
        case authorId = "author_id"
        case authorName = "author_name"
        case authorAvatar = "author_avatar"
        case signature
        case fansNum = "fans_num"
        case noteNum = "note_num"
        case isConcerned = "is_concerned"
        case noteImages = "note_images"
    }
}

// MARK: - API响应模型
struct CommunityListResponse: Codable {
    let list: [CommunityNote]
    let totalPage: Int
    let currentPage: Int
    
    enum CodingKeys: String, CodingKey {
        case list
        case totalPage = "total_page"
        case currentPage = "current_page"
    }
}

struct RecommendAuthorResponse: Codable {
    let list: [RecommendAuthor]
    let totalPage: Int
    let currentPage: Int
    
    enum CodingKeys: String, CodingKey {
        case list
        case totalPage = "total_page"
        case currentPage = "current_page"
    }
}

class APIService: ObservableObject {
    static let shared = APIService()
    private let session = URLSession.shared
    
    private init() {}
    
    // MARK: - 显示登录页面
    private func showLoginView() {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let rootViewController = windowScene.windows.first?.rootViewController else {
            return
        }
        
        // 查找最顶层的视图控制器
        var topViewController = rootViewController
        while let presentedViewController = topViewController.presentedViewController {
            topViewController = presentedViewController
        }
        
        // 如果当前已经是登录页面，则不重复显示
        if topViewController is UIHostingController<LoginView> {
            return
        }
        
        // 创建并显示登录页面
        let loginVC = UIHostingController(rootView: LoginView())
        loginVC.modalPresentationStyle = .fullScreen
        topViewController.present(loginVC, animated: true, completion: nil)
    }
    
    // MARK: - 通用请求方法 (Combine版本)
    public func request<T: Codable>(
        endpoint: APIEndpoint,
        method: HTTPMethod = .GET,
        parameters: [String: Any]? = nil,
        responseType: T.Type
    ) -> AnyPublisher<T, Error> {
        
        var request = URLRequest(url: URL(string: endpoint.fullURL)!)
        request.httpMethod = method.rawValue
        
        // 添加请求头
        APIConfig.headers.forEach { key, value in
            request.setValue(value, forHTTPHeaderField: key)
        }
        
        // 添加Token（如果存在）
        if let token = UserDefaults.standard.string(forKey: APIConfig.tokenName) {
            request.setValue(token, forHTTPHeaderField: APIConfig.tokenName)
        }
        
        // 添加请求参数
        if let parameters = parameters {
            if method == .GET {
                // GET请求参数添加到URL
                var components = URLComponents(string: endpoint.fullURL)!
                components.queryItems = parameters.map { URLQueryItem(name: $0.key, value: "\($0.value)") }
                request.url = components.url
            } else {
                // POST请求参数添加到body
                request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
            }
        }
        
        // 打印请求信息 (Combine版本)
        print("🌐 API Request (Combine):")
        print("   URL: \(request.url?.absoluteString ?? "Unknown")")
        print("   Method: \(request.httpMethod ?? "Unknown")")
        if let headers = request.allHTTPHeaderFields {
            print("   Headers: \(headers)")
        }
        if let parameters = parameters {
            print("   Parameters: \(parameters)")
        }
        if let body = request.httpBody, let bodyString = String(data: body, encoding: .utf8) {
            print("   Body: \(bodyString)")
        }
        
        return session.dataTaskPublisher(for: request)
            .handleEvents(receiveOutput: { output in
                // 打印响应信息
                if let httpResponse = output.response as? HTTPURLResponse {
                    print("📡 API Response (Combine):")
                    print("   Status Code: \(httpResponse.statusCode)")
                }
                if let responseString = String(data: output.data, encoding: .utf8) {
                    print("   Response Data: \(responseString)")
                }
            }, receiveCompletion: { completion in
                if case .failure(let error) = completion {
                    print("❌ API Error (Combine): \(error)")
                }
            })
            .map(\.data)
            .decode(type: APIResponse<T>.self, decoder: JSONDecoder())
            .tryCompactMap { response in
                print("   Parsed Response (Combine): Success=\(response.isSuccess), Message=\(response.message ?? "nil")")
                if response.isSuccess {
                    return response.data
                } else {
                    throw APIError.serverError(response.message ?? "Unknown error")
                }
            }
            .receive(on: DispatchQueue.main)
            .eraseToAnyPublisher()
    }
    
    // MARK: - 通用请求方法 (Async/Await版本)
    public func request<T: Codable>(
        endpoint: APIEndpoint,
        method: HTTPMethod = .GET,
        parameters: [String: Any]? = nil
    ) async throws -> APIResponse<T> {
        
        var request = URLRequest(url: URL(string: endpoint.fullURL)!)
        request.httpMethod = method.rawValue
        
        // 添加请求头
        APIConfig.headers.forEach { key, value in
            request.setValue(value, forHTTPHeaderField: key)
        }
        
        // 添加Token（如果存在）
        if let token = UserDefaults.standard.string(forKey: APIConfig.tokenName) {
            request.setValue(token, forHTTPHeaderField: APIConfig.tokenName)
        }
        
        // 添加请求参数
        if let parameters = parameters {
            if method == .GET {
                // GET请求参数添加到URL
                var components = URLComponents(string: endpoint.fullURL)!
                components.queryItems = parameters.map { URLQueryItem(name: $0.key, value: "\($0.value)") }
                request.url = components.url
            } else {
                // POST请求参数添加到body
                request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
            }
        }
        
        // 打印请求信息
        print("🌐 API Request:")
        print("   URL: \(request.url?.absoluteString ?? "Unknown")")
        print("   Method: \(request.httpMethod ?? "Unknown")")
        if let headers = request.allHTTPHeaderFields {
            print("   Headers: \(headers)")
        }
        if let parameters = parameters {
            print("   Parameters: \(parameters)")
        }
        if let body = request.httpBody, let bodyString = String(data: body, encoding: .utf8) {
            print("   Body: \(bodyString)")
        }
        
        do {
            let (data, response) = try await session.data(for: request)
            
            // 打印响应信息
            if let httpResponse = response as? HTTPURLResponse {
                print("📡 API Response:")
                print("   Status Code: \(httpResponse.statusCode)")
                print("   Headers: \(httpResponse.allHeaderFields)")
            }
            
            if let responseString = String(data: data, encoding: .utf8) {
                print("   Response Data: \(responseString)")
            }
            
            let apiResponse = try JSONDecoder().decode(APIResponse<T>.self, from: data)
            print("   Parsed Response: Success=\(apiResponse.isSuccess), Message=\(apiResponse.message ?? "nil")")
            
            // 检查 token 过期错误码 (402, 401, 410000, 410001, 410002)
            if apiResponse.code == 402 || apiResponse.code == 401 || 
               apiResponse.code == 410000 || apiResponse.code == 410001 || apiResponse.code == 410002 {
                // 清除 token 和登录状态
                UserDefaults.standard.removeObject(forKey: APIConfig.tokenName)
                UserDefaults.standard.removeObject(forKey: "tokenExpirationDate")
                UserDefaults.standard.removeObject(forKey: "userInfo")
                
                // 发送登出通知
                NotificationCenter.default.post(name: NSNotification.Name("UserDidLogout"), object: nil)
                
                // 在主线程中跳转到登录页面
                DispatchQueue.main.async {
                    self.showLoginView()
                }
            }
            
            return apiResponse
        } catch {
            print("❌ API Error: \(error)")
            throw error
        }
    }
    
    // MARK: - 获取首页数据
    func fetchIndexData() async throws -> APIResponse<IndexData> {
        return try await request(
            endpoint: .indexInfo,
            method: .GET
        )
    }
    
    // MARK: - 获取商品分类
    func fetchProductCategories() async throws -> APIResponse<[ProductCategory]> {
        return try await request(
            endpoint: .categoryFirst,
            method: .GET
        )
    }
    
    // MARK: - 获取第三级分类
    func fetchThirdCategories(id: Int) async throws -> APIResponse<[ProductCategory]> {
        return try await request(
            endpoint: .categoryThird(id),
            method: .GET
        )
    }
    
    // MARK: - 获取底部导航配置
    func fetchBottomNavigation() async throws -> APIResponse<BottomNavigationResponse> {
        return try await request(
            endpoint: .bottomNavigation,
            method: .GET
        )
    }
    
    // MARK: - 获取优惠券
    func fetchCoupons(page: Int = 1, limit: Int = 10, type: String = "1", category: Int = 0, merId: Int = 0) async throws -> APIResponse<CouponResponse> {
        let params: [String: Any] = ["page": page, "limit": limit, "type": type, "category": category, "merId": merId]
        return try await request(
            endpoint: .coupons,
            method: .GET,
            parameters: params
        )
    }
    
    // MARK: - 通用请求方法 (支持 Decodable 类型)
    public func request<T: Decodable>(
        endpoint: APIEndpoint,
        method: HTTPMethod = .GET,
        parameters: [String: Any]? = nil
    ) async throws -> DecodableAPIResponse<T> {
        
        var request = URLRequest(url: URL(string: endpoint.fullURL)!)
        request.httpMethod = method.rawValue
        
        // 添加请求头
        APIConfig.headers.forEach { key, value in
            request.setValue(value, forHTTPHeaderField: key)
        }
        
        // 添加Token（如果存在）
        if let token = UserDefaults.standard.string(forKey: APIConfig.tokenName) {
            request.setValue(token, forHTTPHeaderField: APIConfig.tokenName)
        }
        
        // 添加请求参数
        if let parameters = parameters {
            if method == .GET {
                // GET请求参数添加到URL
                var components = URLComponents(string: endpoint.fullURL)!
                components.queryItems = parameters.map { URLQueryItem(name: $0.key, value: "\($0.value)") }
                request.url = components.url
            } else {
                // POST请求参数添加到body
                request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
            }
        }
        
        // 打印请求信息
        print("🌐 API Request (Decodable):")
        print("   URL: \(request.url?.absoluteString ?? "Unknown")")
        print("   Method: \(request.httpMethod ?? "Unknown")")
        if let headers = request.allHTTPHeaderFields {
            print("   Headers: \(headers)")
        }
        if let parameters = parameters {
            print("   Parameters: \(parameters)")
        }
        if let body = request.httpBody, let bodyString = String(data: body, encoding: .utf8) {
            print("   Body: \(bodyString)")
        }
        
        do {
            let (data, response) = try await session.data(for: request)
            
            // 打印响应信息
            if let httpResponse = response as? HTTPURLResponse {
                print("📡 API Response (Decodable):")
                print("   Status Code: \(httpResponse.statusCode)")
                print("   Headers: \(httpResponse.allHeaderFields)")
            }
            
            if let responseString = String(data: data, encoding: .utf8) {
                print("   Response Data: \(responseString)")
            }
            
            let apiResponse = try JSONDecoder().decode(DecodableAPIResponse<T>.self, from: data)
            print("   Parsed Response: Success=\(apiResponse.isSuccess), Message=\(apiResponse.message ?? "nil")")
            
            // 检查 token 过期错误码 (402, 401, 410000, 410001, 410002)
            if apiResponse.code == 402 || apiResponse.code == 401 || 
               apiResponse.code == 410000 || apiResponse.code == 410001 || apiResponse.code == 410002 {
                // 清除 token 和登录状态
                UserDefaults.standard.removeObject(forKey: APIConfig.tokenName)
                UserDefaults.standard.removeObject(forKey: "tokenExpirationDate")
                UserDefaults.standard.removeObject(forKey: "userInfo")
                
                // 发送登出通知
                NotificationCenter.default.post(name: NSNotification.Name("UserDidLogout"), object: nil)
                
                // 在主线程中跳转到登录页面
                DispatchQueue.main.async {
                    self.showLoginView()
                }
            }
            
            return apiResponse
        } catch {
            print("❌ API Error (Decodable): \(error)")
            throw error
        }
    }
    
    // MARK: - 获取DIY数据
    func fetchDIYData(id: Int) async throws -> DecodableAPIResponse<DIYPageData> {
        return try await request(
            endpoint: .diyData(id),
            method: .GET
        )
    }
    
    // MARK: - 根据商品ID列表获取商品
    func fetchProductsByIds(ids: String) async throws -> APIResponse<[Product]> {
        return try await request(
            endpoint: .productByIds(ids),
            method: .GET
        )
    }
    
    // // MARK: - 获取商品列表
    // func fetchProductList(parameters: [String: Any]) async throws -> APIResponse<[Product]> {
    //     return try await request(
    //         endpoint: .productList,
    //         method: .GET,
    //         parameters: parameters
    //     )
    // }
    
    // 获取商品列表（新接口，返回 GoodsListResponse）
    func fetchGoodsList(keyword: String = "", priceOrder: String = "", salesOrder: String = "", page: Int = 1, limit: Int = 20, cid: Int = 0, merId: Int? = nil, cids: String = "") async throws -> APIResponse<GoodsListResponse> {
        var parameters: [String: Any] = [
            "keyword": keyword,
            "priceOrder": priceOrder,
            "salesOrder": salesOrder,
            "page": page,
            "limit": limit,
            "cid": cid,
            "cids": cids
        ]
        
        // 只有当 merId 不为 nil 时才添加到参数中
        if let merId = merId {
            parameters["merId"] = merId
        }
        
        return try await request(
            endpoint: .productList,
            method: .GET,
            parameters: parameters
        )
    }
    
    // MARK: - 获取推荐商品列表
    func fetchRecommendProducts(page: Int = 1, limit: Int = 10, cid: Int = 0) async throws -> APIResponse<ProductListData> {
        let parameters: [String: Any] = [
            "page": page,
            "limit": limit,
            "cid": cid      
        ]
        return try await request(
            endpoint: .recommendProducts,
            method: .GET,
            parameters: parameters
        )
    }
    
    // MARK: - 获取用户等级信息
    // func fetchUserGradeInfo() async throws -> APIResponse<UserGradeInfo> {
    //     return try await request(
    //         endpoint: .userGrade,
    //         method: .GET,
    //         parameters: nil
    //     )
    // }
    
    // MARK: - 获取用户等级经验值信息
    func fetchUserGradeExp() async throws -> APIResponse<UserGradeInfo> {
        return try await request(
            endpoint: .userGradeExp,
            method: .GET,
            parameters: nil
        )
    }
    
    // MARK: - 获取商品详情
    func fetchProductDetail(id: Int, marketingType: String = "", type: String = "", groupActivityId: String = "") async throws -> APIResponse<Product> {
        let params = [
            "id": id,
            "marketingType": marketingType,
            "type": type,
            "groupActivityId": groupActivityId
        ] as [String : Any]
        return try await request(
            endpoint: .productDetail,
            method: .GET,
            parameters: params
        )
    }
    
    // MARK: - 获取商品详情（完整版）
    func fetchGoodsDetail(id: Int, marketingType: Int = 0, type: Int = 0, groupActivityId: String = "") async throws -> APIResponse<GoodsDetailResponse> {
        let params = [
            "id": id,
            "marketingType": marketingType,
            "type": type,
            "groupActivityId": groupActivityId
        ] as [String : Any]
        return try await request(
            endpoint: .productDetail,
            method: .GET,
            parameters: params
        )
    }
    
    // MARK: - 获取商品评论详情
    func fetchProductReplyDetail(productId: Int) async throws -> APIResponse<ProductReplyDetailResponse> {
        return try await request(
            endpoint: .productReplyDetail(productId),
            method: .GET,
            parameters: [:]
        )
    }
    
    // MARK: - 获取商品评论配置
    func fetchProductReplyConfig(productId: Int) async throws -> APIResponse<ProductReplyConfigResponse> {
        return try await request(
            endpoint: .productReplyConfig(productId),
            method: .GET,
            parameters: [:]
        )
    }
    
    // MARK: - 获取用户积分（购物时使用）
    func fetchShoppingUserIntegral() async throws -> APIResponse<UserIntegralResponse> {
        return try await request(
            endpoint: .shoppingUserIntegral,
            method: .GET,
            parameters: [:]
        )
    }
    
    // MARK: - 获取购物车数量
    func fetchCartCount1(numType: Bool = true, type: String = "total") async throws -> APIResponse<CartCountResponse> {
        let params = [
            "numType": numType,
            "type": type
        ] as [String : Any]
        return try await request(
            endpoint: .cartCount1,
            method: .GET,
            parameters: params
        )
    }
    
    
    // MARK: - 获取购物车列表
    func fetchCartList(parameters: [String: Any] = [:]) async throws -> APIResponse<[CartItem]> {
        return try await request(
            endpoint: .cartList,
            method: .GET,
            parameters: parameters
        )
    }
    
    // MARK: - 添加到购物车
    func addToCart(data: [String: Any]) async throws -> APIResponse<String> {
        return try await request(
            endpoint: .cartAdd,
            method: .POST,
            parameters: data
        )
    }
    
    // MARK: - 获取购物车数量
    func fetchCartCount(numType: Bool = true, type: String = "") async throws -> APIResponse<Int> {
        let params = ["numType": numType, "type": type] as [String : Any]
        return try await request(
            endpoint: .cartCount,
            method: .GET,
            parameters: params
        )
    }
    
    // MARK: - 修改购物车数量
    func updateCartQuantity(cartId: Int, number: Int) async throws -> APIResponse<String> {
        let params = ["id": cartId, "number": number] as [String : Any]
        return try await request(
            endpoint: .cartNum,
            method: .POST,
            parameters: params
        )
    }
    
    // MARK: - 删除购物车商品
    func deleteCartItems(ids: [Int]) async throws -> APIResponse<String> {
        let params = ["ids": ids] as [String : Any]
        return try await request(
            endpoint: .cartDelete,
            method: .POST,
            parameters: params
        )
    }
    
    // MARK: - 购物车重选提交
    func resetCart(data: [String: Any]) async throws -> APIResponse<String> {
        return try await request(
            endpoint: .cartResetCart,
            method: .POST,
            parameters: data
        )
    }
    
    // MARK: - 购物车商品价格计算
    func calculateCartPrice(data: [String: Any]) async throws -> APIResponse<String> {
        return try await request(
            endpoint: .cartCalculatePrice,
            method: .POST,
            parameters: data
        )
    }
    
    // MARK: - 购物车移入收藏
    func cartToCollect(ids: [Int]) async throws -> APIResponse<String> {
        let params = ["ids": ids] as [String : Any]
        return try await request(
            endpoint: .cartToCollect,
            method: .POST,
            parameters: params
        )
    }
    
    // MARK: - 批量添加购物车
    func batchAddToCart(data: [String: Any]) async throws -> APIResponse<String> {
        return try await request(
            endpoint: .cartBatchAdd,
            method: .POST,
            parameters: data
        )
    }
    
    // MARK: - 获取用户信息
    func fetchUserInfo() async throws -> APIResponse<UserInfo> {
        return try await request(
            endpoint: .userInfo,
            method: .GET
        )
    }
    
    // MARK: - 获取文章列表
    func fetchArticleList(cid: Int = 0, page: Int = 1, limit: Int = 10) async throws -> APIResponse<[Article]> {
        let params = ["cid": cid, "page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .articleList(cid: cid),
            method: .GET,
            parameters: params
        )
    }
    
    // MARK: - 发现页面相关API方法
    
    // 获取文章轮播图列表
    func fetchArticleBannerList() async throws -> APIResponse<[BannerItem]> {
        return try await request(
            endpoint: .articleBannerList,
            method: .GET
        )
    }
    
    // 获取发现页面内容列表
    func fetchDiscoverList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<[Article]> {
        let params = ["page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .discoverList,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取社区分类列表
    func fetchCommunityCategoryList() async throws -> APIResponse<[ProductCategory]> {
        return try await request(
            endpoint: .communityCategoryList,
            method: .GET
        )
    }
    
    // 获取推荐作者列表
    func fetchRecommendAuthorList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<[UserInfo]> {
        let params = ["page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .recommendAuthorList,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取话题数量
    func fetchTopicCount() async throws -> APIResponse<Int> {
        return try await request(
            endpoint: .topicCount,
            method: .GET
        )
    }
    
    // 获取用户主页信息
    func fetchUserHome(userId: Int) async throws -> APIResponse<UserInfo> {
        let params = ["userId": userId] as [String : Any]
        return try await request(
            endpoint: .userHome,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取笔记作者列表
    func fetchNoteAuthorList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<[UserInfo]> {
        let params = ["page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .noteAuthorList,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取关注列表
    func fetchFollowList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<[UserInfo]> {
        let params = ["page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .followList,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取回复列表
    func fetchReplyList(noteId: Int, page: Int = 1, limit: Int = 10) async throws -> APIResponse<[String]> {
        let params = ["noteId": noteId, "page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .replyList,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取话题列表
    func fetchTopicList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<[String]> {
        let params = ["page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .topicList,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取推荐话题列表
    func fetchTopicRecommendList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<[String]> {
        let params = ["page": page, "limit": limit] as [String : Any]
        return try await request(
            endpoint: .topicRecommendList,
            method: .GET,
            parameters: params
        )
    }
    
    // 获取笔记详情
    func fetchNoteDetail(noteId: Int) async throws -> APIResponse<Article> {
        let params = ["noteId": noteId] as [String : Any]
        return try await request(
            endpoint: .noteDetail,
            method: .GET,
            parameters: params
        )
    }
    
    // MARK: - 配置相关API
    
    // 获取主题配置
    func fetchThemeConfig() async throws -> APIResponse<ConfigData> {
        return try await request(
            endpoint: .themeConfig,
            method: .GET,
            parameters: nil
        )
    }
    
    // 获取主题配置 (Combine版本)
    func fetchThemeConfigPublisher() -> AnyPublisher<ConfigData, Error> {
        return request(
            endpoint: .themeConfig,
            method: .GET,
            parameters: nil,
            responseType: ConfigData.self
        )
    }

    
    // MARK: - 社区相关接口
    
    // 获取社区分类列表
    func getCommunityCategoryList() async throws -> APIResponse<[CommunityCategory]> {
        return try await request(
            endpoint: .communityCategoryList,
            method: .GET
        )
    }
    
    // 获取发现列表
    func getDiscoverList(categoryId: String = "", page: Int = 1, limit: Int = 10) async throws -> APIResponse<CommunityListResponse> {
        var parameters: [String: Any] = [
            "page": page,
            "limit": limit
        ]
        if !categoryId.isEmpty {
            parameters["categoryId"] = categoryId
        }
        
        return try await request(
            endpoint: .discoverList,
            method: .GET,
            parameters: parameters
        )
    }
    
    // 获取关注列表
    func getFollowList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<CommunityListResponse> {
        let parameters: [String: Any] = [
            "page": page,
            "limit": limit
        ]
        
        return try await request(
            endpoint: .followList,
            method: .GET,
            parameters: parameters
        )
    }
    
    // 获取推荐作者列表
    func getRecommendAuthorList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<RecommendAuthorResponse> {
        let parameters: [String: Any] = [
            "page": page,
            "limit": limit
        ]
        
        return try await request(
            endpoint: .recommendAuthorList,
            method: .GET,
            parameters: parameters
        )
    }
    
    // 关注/取消关注作者
    func followAuthor(authorId: String) async throws -> APIResponse<Bool> {
        return try await request(
            endpoint: .followAuthor(authorId: authorId),
            method: .POST
        )
    }
    
    // 点赞/取消点赞内容
    func likeNote(noteId: String) async throws -> APIResponse<Bool> {
        return try await request(
            endpoint: .likeNote(noteId: noteId),
            method: .POST
        )
    }
        
    // MARK: - 获取用户中心信息
    func fetchUserCenterInfo() async throws -> APIResponse<UserInfoData> {
        return try await request(
            endpoint: .getUserInfo,
            method: .GET
        )
    }
    
    // MARK: - 获取用户中心菜单
    func fetchUserCenterMenu() async throws -> APIResponse<CenterMenuData> {
        return try await request(
            endpoint: .userCenterMenu,
            method: .GET
        )
    }
    
    // MARK: - 获取用户积分记录（带分页）
    func fetchUserIntegralList(page: Int = 1, limit: Int = 10) async throws -> APIResponse<IntegralListResponse> {
        let parameters: [String: Any] = [
            "page": page,
            "limit": limit
        ]
        return try await request(
            endpoint: .userIntegralList,
            method: .GET,
            parameters: parameters
        )
    }
    
    // MARK: - 获取用户积分信息
    func fetchUserIntegralInfo() async throws -> APIResponse<IntegralInfo> {
        return try await request(
            endpoint: .userIntegralInfo,
            method: .GET,
            parameters: nil
        )
    }
    
    // MARK: - 获取用户余额记录
    func fetchUserMoney() async throws -> APIResponse<BalanceResponse> {
        return try await request(
            endpoint: .userMoney,
            method: .GET
        )
    }
    
    // MARK: - 获取用户余额详情
    func fetchUserMoneyInfo() async throws -> APIResponse<BalanceInfo> {
        return try await request(
            endpoint: .userMoneyInfo,
            method: .GET
        )
    }
    
    // MARK: - 获取用户签到数据
    func fetchUserSign(month: String? = nil) async throws -> APIResponse<SignData> {
        var parameters: [String: Any]? = nil
        if let month = month {
            parameters = ["month": month]
        }
        
        return try await request(
            endpoint: .userSignInfo,
            method: .GET,
            parameters: parameters
        )
    }
    
    // MARK: - 获取签到记录列表（带分页）
    func fetchSignRecordList(page: Int = 1, limit: Int = 20) async throws -> APIResponse<SignRecordListResponse> {
        let parameters: [String: Any] = [
            "page": page,
            "limit": limit
        ]
        return try await request(
            endpoint: .signRecordList,
            method: .GET,
            parameters: parameters
        )
    }
    
    
    // MARK: - 获取用户信息
    func fetchUserProfile() async throws -> APIResponse<UserProfile> {
        return try await request(
            endpoint: .UserProfile,
            method: .GET
        )
    }
    
    // MARK: - 更新用户信息
    func updateUserProfile(data: [String: Any]) async throws -> APIResponse<UserProfile> {
        return try await request(
            endpoint: .UserProfileEdit,
            method: .POST,
            parameters: data
        )
    }
    
    // MARK: - 获取地址列表
    func fetchAddressList() async throws -> APIResponse<[AddressItem]> {
        return try await request(
            endpoint: .userAddress,
            method: .GET
        )
    }
    
    // MARK: - 获取收藏列表（商品）
    // func fetchCollectionList(page: Int = 1, limit: Int = 20) async throws -> APIResponse<CollectionResponse> {
    //     let parameters: [String: Any] = [
    //         "page": page,
    //         "limit": limit
    //     ]
        
    //     return try await request(
    //         endpoint: .userCollection,
    //         method: .GET,
    //         parameters: parameters
    //     )
    // }
    
    // MARK: - 获取商户收藏列表
    func fetchMerchantCollectionList(page: Int = 1, limit: Int = 20) async throws -> APIResponse<MerchantCollectionResponse> {
        let parameters: [String: Any] = [
            "page": page,
            "limit": limit
        ]
        
        return try await request(
            endpoint: .userCollection,
            method: .GET,
            parameters: parameters
        )
    }
    
    // MARK: - 取消商户收藏
    func cancelMerchantCollection(merId: Int) async throws -> APIResponse<EmptyResponse> {
        return try await request(
            endpoint: .merchantCollectionCancel(merId),
            method: .POST,
            parameters: nil
        )
    }
    
    // MARK: - 添加地址
    func addAddress(address: AddressItem) async throws -> APIResponse<EmptyResponse> {
        var params: [String: Any] = [
            "id": 0,
            "realName": address.realName ?? "",
            "phone": address.phone ?? "",
            "province": address.province ?? "",
            "city": address.city ?? "",
            "district": address.district ?? "",
            "detail": address.detail ?? "",
            "isDefault": address.isDefault ?? false
        ]
        
        // 地区ID必须存在且不能为空
        if let provinceId = address.provinceId, provinceId > 0 {
            params["provinceId"] = provinceId
        }
        if let cityId = address.cityId, cityId > 0 {
            params["cityId"] = cityId
        }
        if let districtId = address.districtId, districtId > 0 {
            params["districtId"] = districtId
        }
        if let street = address.street, !street.isEmpty {
            params["street"] = street
        }
        
        return try await request(
            endpoint: .userAddressAdd,
            method: .POST,
            parameters: params
        )
    }
    
    // MARK: - 更新地址
    func updateAddress(address: AddressItem) async throws -> APIResponse<EmptyResponse> {
        var params: [String: Any] = [
            "id": address.id,
            "realName": address.realName ?? "",
            "phone": address.phone ?? "",
            "province": address.province ?? "",
            "city": address.city ?? "",
            "district": address.district ?? "",
            "detail": address.detail ?? "",
            "isDefault": address.isDefault ?? false
        ]
        
        // 地区ID必须存在且不能为空
        if let provinceId = address.provinceId, provinceId > 0 {
            params["provinceId"] = provinceId
        }
        if let cityId = address.cityId, cityId > 0 {
            params["cityId"] = cityId
        }
        if let districtId = address.districtId, districtId > 0 {
            params["districtId"] = districtId
        }
        if let street = address.street, !street.isEmpty {
            params["street"] = street
        }
        
        return try await request(
            endpoint: .userAddressEdit(address.id),
            method: .POST,
            parameters: params
        )
    }
    
    // MARK: - 删除地址
    func deleteAddress(id: Int) async throws -> APIResponse<EmptyResponse> {
        return try await request(
            endpoint: .userAddressDelete(id),
            method: .POST
        )
    }
    
    // MARK: - 设置默认地址
    func setDefaultAddress(id: Int) async throws -> APIResponse<EmptyResponse> {
        return try await request(
            endpoint: .userAddressDefault(id),
            method: .POST
        )
    }
    
    // MARK: - 获取城市列表
    func fetchCityList(parentId: Int, regionType: Int) async throws -> APIResponse<[CityItem]> {
        return try await request(
            endpoint: .cityList(parentId: parentId, regionType: regionType),
            method: .GET
        )
    }
    
    // MARK: - 商户入驻相关API
    
    // 获取入驻协议
    func fetchMerchantAgreement() async throws -> APIResponse<String> {
        return try await request(
            endpoint: .agreementInfo,
            method: .GET,
            parameters: ["type": "merincomminginfo"]
        )
    }
    
    // 获取商户分类列表
    func fetchMerchantCategories() async throws -> APIResponse<[MerchantCategory]> {
        return try await request(
            endpoint: .merchantCategoryList,
            method: .GET,
            parameters: nil
        )
    }
    
    // 获取商户类型列表
    func fetchMerchantTypes() async throws -> APIResponse<[MerchantType]> {
        return try await request(
            endpoint: .merchantTypeList,
            method: .GET,
            parameters: nil
        )
    }
    
    // 发送商户入驻验证码
    func sendMerchantSettledCode(phone: String) async throws -> APIResponse<EmptyResponse> {
        return try await request(
            endpoint: .merchantSendSettledCode,
            method: .POST,
            parameters: ["phone": phone]
        )
    }
    
    
    // 获取推广佣金数据
    func fetchPromotionData() async throws -> APIResponse<PromotionData> {
        return try await request(
            endpoint: .userSpread,
            method: .GET,
            parameters: nil
        )
    }
    
    // 上传图片
    func uploadImage(imageData: Data) async throws -> APIResponse<UploadImageResponse> {
        // 创建multipart表单数据
        let boundary = "Boundary-\(UUID().uuidString)"
        var body = Data()
        
        // 添加图片数据（参数名使用 multipart）
        body.append("--\(boundary)\r\n".data(using: .utf8)!)
        body.append("Content-Disposition: form-data; name=\"multipart\"; filename=\"image.jpg\"\r\n".data(using: .utf8)!)
        body.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
        body.append(imageData)
        body.append("\r\n".data(using: .utf8)!)
        body.append("--\(boundary)--\r\n".data(using: .utf8)!)
        
        // 创建自定义请求
        let url = URL(string: "\(APIConfig.baseURL)\(APIEndpoint.uploadImage.path)")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        // 添加token（使用 Authorization 格式）
        if let token = UserDefaults.standard.string(forKey: APIConfig.tokenName), !token.isEmpty {
            request.setValue(token, forHTTPHeaderField: "Authorization")
            request.setValue(token, forHTTPHeaderField: APIConfig.tokenName)  // 兼容两种格式
        }
        
        request.httpBody = body
        
        // 打印调试信息
        print("📤 上传图片请求:")
        print("URL: \(url.absoluteString)")
        print("Content-Type: multipart/form-data; boundary=\(boundary)")
        print("Body size: \(body.count) bytes")
        
        let (data, response) = try await URLSession.shared.data(for: request)
        
        // 打印响应信息
        if let httpResponse = response as? HTTPURLResponse {
            print("📥 上传图片响应:")
            print("Status Code: \(httpResponse.statusCode)")
            print("Headers: \(httpResponse.allHeaderFields)")
            if let responseString = String(data: data, encoding: .utf8) {
                print("Response Data: \(responseString)")
            }
            
            // 检查状态码
            guard httpResponse.statusCode == 200 else {
                let errorMessage = String(data: data, encoding: .utf8) ?? "上传失败"
                throw NSError(domain: "UploadError", code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey: errorMessage])
            }
        }
        
        let decoder = JSONDecoder()
        let result = try decoder.decode(APIResponse<UploadImageResponse>.self, from: data)
        
        // 检查响应码
        if result.code != 200 {
            throw NSError(domain: "UploadError", code: result.code, userInfo: [NSLocalizedDescriptionKey: result.message ?? "上传失败"])
        }
        
        return result
    }
    
    // 提交商户入驻申请
    func submitMerchantSettled(data: MerchantSettledData) async throws -> APIResponse<EmptyResponse> {
        return try await request(
            endpoint: .merchantSettledApply,
            method: .POST,
            parameters: data.dictionary
        )
    }
    
    // MARK: - 优惠券相关API
    
    // 获取用户优惠券列表（usable/unusable）
    func fetchUserCouponsList(type: String, page: Int = 1, limit: Int = 20) async throws -> APIResponse<UserCouponResponse> {
        let parameters: [String: Any] = [
            "page": page,
            "limit": limit,
            "type": type
        ]
        return try await request(
            endpoint: .userCouponsList(type: type),
            method: .GET,
            parameters: parameters
        )
    }
    
    // 获取领券中心列表
    func fetchCouponCollectionCenter(category: Int = 0, page: Int = 1, limit: Int = 15) async throws -> APIResponse<CouponCollectionResponse> {
        let parameters: [String: Any] = [
            "category": category,
            "page": page,
            "limit": limit
        ]
        return try await request(
            endpoint: .couponCollectionCenter,
            method: .GET,
            parameters: parameters
        )
    }
    
    // 领取优惠券
    func receiveCoupon(couponId: Int) async throws -> APIResponse<EmptyResponse> {
        return try await request(
            endpoint: .couponReceive(couponId),
            method: .POST,
            parameters: nil
        )
    }
    
    // MARK: - 获取商品优惠券列表
    func fetchProductCouponList(productId: Int, page: Int = 1, limit: Int = 20, category: Int = 0) async throws -> APIResponse<ProductCouponListResponse> {
        let parameters: [String: Any] = [
            "productId": productId,
            "page": page,
            "limit": limit,
            "category": category
        ]
        return try await request(
            endpoint: .productCouponList(productId),
            method: .GET,
            parameters: parameters
        )
    }
    
    // MARK: - 订单相关API
    
    // 获取订单列表
    func fetchOrderList(status: Int = -1, page: Int = 1, limit: Int = 20, keywords: String = "", secondType: Int = 0) async throws -> APIResponse<OrderListResponse> {
        let parameters: [String: Any] = [
            "status": status,
            "page": page,
            "limit": limit,
            "keywords": keywords,
            "secondType": secondType
        ]
        return try await request(
            endpoint: .orderList,
            method: .GET,
            parameters: parameters
        )
    }
    
    // 获取订单详情
    func fetchOrderDetail(orderNo: String) async throws -> APIResponse<OrderDetailData> {
        return try await request(
            endpoint: .orderDetail(orderNo),
            method: .GET,
            parameters: nil
        )
    }
}

// MARK: - HTTP方法枚举
enum HTTPMethod: String {
    case GET = "GET"
    case POST = "POST"
    case PUT = "PUT"
    case DELETE = "DELETE"
}

// MARK: - API错误枚举
enum APIError: Error, LocalizedError {
    case invalidURL
    case noData
    case decodingError
    case serverError(String)
    case networkError
    
    var errorDescription: String? {
        switch self {
        case .invalidURL:
            return "无效的URL"
        case .noData:
            return "没有数据"
        case .decodingError:
            return "数据解析错误"
        case .serverError(let message):
            return message
        case .networkError:
            return "网络连接错误"
        }
    }
}
